from models.recognizer import SpeechRecognizer
from models.translator import Translator
from audio.stream import AudioStream
import threading, queue, time


class RealTimeProcessorMT:
    def __init__(self, input_source="mic", file_path=None):
        self.audio_stream = AudioStream(source=input_source, file_path=file_path)
        self.recognizer = SpeechRecognizer()
        self.translator = Translator()
        self.audio_queue = queue.Queue(maxsize=10)
        self.text_queue = queue.Queue(maxsize=10)
        self.running = True

    def run(self):
        threading.Thread(target=self._produce, daemon=True).start()
        threading.Thread(target=self._asr_worker, daemon=True).start()
        threading.Thread(target=self._translate_worker, daemon=True).start()
        print("🚀 实时识别启动, 按 Ctrl+C 停止...")
        try:
            while True:
                time.sleep(0.1)
        except KeyboardInterrupt:
            self.running = False

    def _produce(self):
        for chunk in self.audio_stream.generator():
            if not self.running: break
            self.audio_queue.put(chunk)

    def _asr_worker(self):
        while self.running:
            try:
                chunk = self.audio_queue.get(timeout=1)
                text = self.recognizer.transcribe(chunk)
                if text: self.text_queue.put(text)
            except:
                continue

    def _translate_worker(self):
        while self.running:
            try:
                text = self.text_queue.get(timeout=1)
                translation = self.translator.translate(text)
                print(f"[识别] {text}\n[翻译] {translation}\n")
            except:
                continue
